package com.rjwh.dingdong.client.service;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.aishua.lib.utils.AsLog;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.guide.MainActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.util.FileUtils;
import com.wby.utility.AppUtil;

import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import java.io.File;

/**
 * APP自动升级服务
 *
 * @author deyi
 */
public class AppUpgradeServer {
    private final static String TAG = "AppUpgradeServer";
    static String app_dowload_url;
    private static Notification updateNotify;

    private static NotificationManager updateNotifMg;

    private final static int UPDATE_NOTIFY = 10000;

    /**
     * 检测升级
     *
     * @return
     */
    public static void checkUpdata(final Context context,
                                   final boolean fs) {

        // 从AndroidManifest.xml的meta-data中读取SDK配置信息
        String packageName = context.getPackageName();
        String baiduMobAd_CHANNE="dingdong";
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                baiduMobAd_CHANNE = appInfo.metaData.getString("BaiduMobAd_CHANNEL");
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        String aurl = LocalConstant.VERSION_CHECK + "?" + "platform=android" + "&ostype=1" + "&versioncode="
                + (int) AppUtil.GetVersionCode(context)+"&channe="+baiduMobAd_CHANNE;
        AsLog.d("AppUpgradeServer", aurl);
        MyApplication.http.get(aurl, new AjaxCallBack<String>() {
            @SuppressLint("ShowToast")
            @Override
            public void onSuccess(String t) {
                // TODO Auto-generated method stub
                super.onSuccess(t);

                try {
                    // 检测版本如果发现 服务端版本比本地大 就弹出升级提示
                    JSONObject jb = new JSONObject(t);
                    AsLog.d(TAG, jb.toString());
                    JSONObject versioninfo = jb.getJSONObject("versioninfo");
                    String versionname = versioninfo.getString("versionname");
                    String force = versioninfo.getString("force");

                    if ("1".equals(versioninfo.getString("update"))) {
                        app_dowload_url = versioninfo.getString("downloadurl");
                        AsLog.d(TAG, app_dowload_url);
                        if ("1".equals(force)) {
                            updataApp(context);
                        } else {
                            showCheckUpdataDialog(context, fs, versionname);
                        }
                    } else {
                        if (fs)
                            Toast.makeText(context, "您当前已经是最新版本了", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(Throwable t, String strMsg) {

            }

            ;
        });

    }

    /**
     * 升级提示框
     *
     * @param versionname 版本号
     * @return
     */
    private static void showCheckUpdataDialog(final Context context,
                                              final boolean fs, String versionname) {

        final AlertDialog checkUpdataDialog = new AlertDialog.Builder(context)
                .create();
        checkUpdataDialog.show();
        Window window = checkUpdataDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setContentView(R.layout.dialog_update_check);
        window.setGravity(Gravity.CENTER);
        checkUpdataDialog.setCanceledOnTouchOutside(false);
        TextView checkUpdataTv = (TextView) window
                .findViewById(R.id.update_check_tv);
        checkUpdataTv.setText("当前版本为" + AppUtil.GetVersionName(context)
                + " , 请更新到" + versionname);
        TextView callCancleBtn = (TextView) window
                .findViewById(R.id.update_check_cancel);
        TextView callOkBtn = (TextView) window
                .findViewById(R.id.update_check_confirm);
        callOkBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                checkUpdataDialog.dismiss();
                updataApp(context);
            }

        });

        callCancleBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                checkUpdataDialog.dismiss();
            }
        });

    }

    /**
     * 升级
     */
    private static void updataApp(final Context context) {
        // if (app_dowload_url != null || !app_dowload_url.equals("")) {
        // Intent downloadIntent = new Intent(Intent.ACTION_VIEW,
        // Uri.parse(app_dowload_url));
        // context.startActivity(downloadIntent);
        // }

        showNotification(context);

        final File filePath = new File(FileUtils.getAPKStorageDirectory(), "/"
                + System.currentTimeMillis() + "Whrjwh_master.apk");
        if (app_dowload_url != null) {
            MyApplication.http.download(app_dowload_url, filePath.getPath(),
                    new AjaxCallBack<File>() {
                        @Override
                        public void onLoading(long count, long current) {
                            // TODO Auto-generated method stub
                            super.onLoading(count, current);
                            int progerss = (int) ((current * 100 / count));
                            updateNotify.contentView.setProgressBar(
                                    R.id.notificationProgress, 100, progerss,
                                    false);
                            updateNotify.contentView.setTextViewText(
                                    R.id.notificationPercent, progerss + "%");
                            updateNotifMg.notify(UPDATE_NOTIFY, updateNotify);
                        }

                        @Override
                        public void onSuccess(File t) {
                            // TODO Auto-generated method stub
                            super.onSuccess(t);
                            // Toast.makeText(context, "下载成功",
                            // Toast.LENGTH_LONG).show();
                            updateNotifMg.cancel(UPDATE_NOTIFY);
                            insterApp(context, t);
                        }

                        @Override
                        public void onFailure(Throwable t, String strMsg) {
                            // TODO Auto-generated method stub
                            super.onFailure(t, strMsg);
                            Toast.makeText(context, t.getMessage(),
                                    Toast.LENGTH_LONG).show();
                            updateNotifMg.cancel(UPDATE_NOTIFY);
                        }

                        @Override
                        public void onStart() {
                            // TODO Auto-generated method stub
                            super.onStart();

                            updateNotify.contentView.setProgressBar(
                                    R.id.notificationProgress, 100, 0, false);
                            updateNotify.contentView.setTextViewText(
                                    R.id.notificationPercent, "0%");
                            updateNotifMg.notify(UPDATE_NOTIFY, updateNotify);
                        }
                    });
        }
    }

    private static void showNotification(final Context context) {
        updateNotify = new Notification();
        updateNotifMg = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        updateNotify.contentView = new RemoteViews(context.getPackageName(),
                R.layout.notification_version);
        updateNotify.icon = android.R.drawable.stat_sys_download;
        Intent i = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i,
                0);
        updateNotify.contentIntent = pendingIntent;
        updateNotifMg.notify(UPDATE_NOTIFY, updateNotify);
    }

    static void insterApp(Context context, File t) {

        Uri uri = Uri.fromFile(t);
        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setDataAndType(uri,
                "application/vnd.android.package-archive");
        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(installIntent);
        long al[] = {80L, 80L};
        updateNotify.vibrate = al;
        updateNotify.icon = android.R.drawable.stat_sys_download_done;
        updateNotify.flags = Notification.FLAG_AUTO_CANCEL;
        updateNotify.defaults = Notification.DEFAULT_SOUND;
        updateNotify.contentIntent = PendingIntent.getActivity(context, 0,
                installIntent, 0);
        updateNotify.contentView.setTextViewText(R.id.notificationTitle,
                "下载完成,点击安装");
        updateNotifMg.notify(UPDATE_NOTIFY, updateNotify);

    }
}
